<template>
  <div class="course-management">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="searchForm">
        <div class="search-form-grid">
          <el-form-item label="课程名称" class="search-item">
            <el-input v-model="searchForm.courseName" placeholder="输入课程名称" clearable />
          </el-form-item>

          <el-form-item label="教师" class="search-item">
            <el-select v-model="searchForm.teacherId" placeholder="选择教师" clearable filterable remote
              :remote-method="queryTeacher">
              <el-option v-for="teacher in teachers" :key="teacher.id" :label="teacher.teacherName"
                :value="teacher.id" />
            </el-select>
          </el-form-item>

          <el-form-item label="学员" class="search-item">
            <el-select v-model="searchForm.studentId" placeholder="选择学员" clearable filterable remote
              :remote-method="queryStudent">
              <el-option v-for="student in students" :key="student.id" :label="student.studentName"
                :value="student.id" />
            </el-select>
          </el-form-item>

          <el-form-item label="乐器分类" class="search-item">
            <el-select v-model="searchForm.instrumentId" placeholder="选择乐器分类" clearable>
              <el-option v-for="instrument in instrumentsOptions" :key="instrument.id" :label="instrument.icName"
                :value="instrument.id" />
            </el-select>
          </el-form-item>

          <el-form-item label="课程类型" class="search-item">
            <el-select v-model="searchForm.type" placeholder="全部类型" clearable>
              <el-option label="一对一" value="1" />
              <el-option label="小组课" value="2" />
              <el-option label="公开课" value="3" />
              <el-option label="试听课" value="4" />
            </el-select>
          </el-form-item>

          <el-form-item label="教室" class="search-item">
            <el-select v-model="searchForm.classroomId" placeholder="全部教室" clearable>
              <el-option v-for="classroom in classroomList" 
              :key="classroom.id" :label="classroom.classroomName" :value="classroom.id" />
            </el-select>
          </el-form-item>

          <div class="search-buttons">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </div>
        </div>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-buttons" v-permission="['editCourse']">
      <el-button type="primary" @click="showAddDialog">
        <el-icon>
          <Plus />
        </el-icon>新增课程
      </el-button>
    </div>

    <!-- 课程列表 -->
    <el-card shadow="never" class="table-card">
      <el-table :data="courses" style="width: 100%" v-loading="loading">
        <el-table-column prop="courseName" label="课程名称" width="200" />
        <el-table-column label="上课时间" width="200">
          <template #default="{ row }">
            {{ getSchoolTime(row) }}
          </template>
        </el-table-column>
        <el-table-column label="余 / 消 / 总（课时）" width="150" >
          <template #default="{ row }">
            {{ row.totalLessons - row.finishedLessons }} / {{ row.finishedLessons }} / {{ row.totalLessons }}
          </template>
        </el-table-column>
        <el-table-column prop="teacherName" label="教师" width="120" />
        <el-table-column prop="studentName" label="学员" width="120" />
        <el-table-column prop="classroomName" label="教室" width="120" />
        <el-table-column prop="icName" label="乐器分类" width="120" />
        <el-table-column prop="type" label="课程类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getCourseTypeTag(row.type)">
              {{ formatCourseType(row.type) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" fixed="right" v-permission="['editCourse']">
          <template #default="{ row }">
            <el-button type="primary" link @click="showEditDialog(row)">编辑</el-button>
            <el-button :disabled="row.finishedLessons === row.totalLessons" type="success" link @click="showCourseConsumptionEdit(row)">消课</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
          :total="pagination.total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <course-edit v-model="editVisible" :course-data="currentCourse" :mode="editMode" :teachers="teachers"
      :queryTeacher="queryTeacher" :instrumentsOptions="instrumentsOptions" :classroomList="classroomList"
  @success="handleEditSuccess"
      @updateTeachers="updateTeachers" />

    <!-- 编辑对话框 -->
    <CourseConsumptionEdit v-model="courseConsumptionVisible" :course="currentCourse" @submit="handleEditSubmit"
      @close="courseConsumptionVisible = false" />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import CourseEdit from './CourseEdit.vue'
import CourseConsumptionEdit from './CourseConsumptionEdit.vue'
import { getCourses, deleteCourse, addCourse, updateCourse } from '@/api/course'
import { getInstrumentList } from '@/api/instrument.js'
import { addCourseRecord } from '@/api/courseRecord'
import { getClassroomListAll } from '@/api/classroom'
const instrumentsOptions = ref([])
const classroomList = ref([])


const students = ref([])

import { getStudentList } from '@/api/student'

const queryStudent = async (query) => {
  const result = await getStudentList({ page: 1, pageSize: 10, studentName: query })
  students.value = result.data.list
}
getInstrumentList().then(res => {
  instrumentsOptions.value = res.data
})
getClassroomListAll().then(res => {
  classroomList.value = res.data
})
// 搜索表单
const searchForm = reactive({
  courseName: '',
  teacherId: '',
  studentId: '',
  instrumentId: '',
  type: '',
  classroomId: ''
})

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 课程列表数据
const courses = ref([])
const loading = ref(false)

// 教师和学员数据
const teachers = ref([])

import { getTeachers } from '@/api/teacher.js'
const queryTeacher = (query) => {
  getTeachers({
    keyword: query,
    status: '1',
    page: 1,
    pageSize: 5
  }).then(res => {
    teachers.value = res.data.list
  })
}

// 对话框控制
const editVisible = ref(false)
const courseConsumptionVisible = ref(false)
const currentCourse = ref(null)
const editMode = ref('add') // 'add' or 'edit'



// 获取课程列表
const fetchCourses = async () => {
  loading.value = true
  try {
    const res = await getCourses({
      page: pagination.current,
      pageSize: pagination.size,
      ...searchForm
    })
    courses.value = res.data.list.map(el => {
      return {
        ...el,
        repeatWeekly: el.repeatWeekly.split(',')
      }
    })
    pagination.total = res.data.total
  } catch (error) {
    ElMessage.error('获取课程列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索课程
const handleSearch = () => {
  pagination.current = 1
  fetchCourses()
}

// 重置搜索
const resetSearch = () => {
  searchForm.courseName = ''
  searchForm.teacherId = ''
  searchForm.instrumentId = ''
  searchForm.studentId = ''
  searchForm.type = ''
  searchForm.classroomId = ''
  handleSearch()
}

// 分页变化
const handleSizeChange = (size) => {
  pagination.size = size
  fetchCourses()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  fetchCourses()
}

// 显示新增对话框
const showAddDialog = () => {
  editMode.value = 'add'
  currentCourse.value = null
  editVisible.value = true
}

const showCourseConsumptionEdit = (course) => {
  currentCourse.value = { ...course }
  courseConsumptionVisible.value = true
}

const handleEditSubmit = async (formData) => {
  try {
    await addCourseRecord({
      ...formData,
      courseId: currentCourse.value.id
    })
    ElMessage.success('消课成功')
    fetchCourses()
  } catch (error) {
    ElMessage.error('消课失败')
  }
  // try {
  //   await updateCourseRecord({
  //     ...currentCourse.value,
  //     ...formData
  //   })
  //   ElMessage.success('消课成功')
  //   editVisible.value = false
  //   fetchCourses()
  // } catch (error) {
  //   ElMessage.error('消课失败')      
  // }
}

// 显示编辑对话框
const showEditDialog = (course) => {
  editMode.value = 'edit'
  currentCourse.value = { ...course }
  editVisible.value = true
}

// 删除课程
const handleDelete = (course) => {
  ElMessageBox.confirm(`确定要删除课程【${course.courseName}】吗？删除后，相关数据将无法恢复！`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteCourse(course.id)
      ElMessage.success('删除成功')
      fetchCourses()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 编辑成功回调
const handleEditSuccess = async (course) => {
  if (editMode.value === 'add') {
    await addCourse(course)
    ElMessage.success('新增课程成功')
  } else {
    await updateCourse(course)
    ElMessage.success('更新课程信息成功')
  }
  fetchCourses()
}

// 格式化课程类型
const formatCourseType = (type) => {
  const map = {
    '1': '一对一',
    '2': '小组课',
    '3': '公开课',
    '4': '试听课'
  }
  return map[type] || type
}

// 获取课程类型标签样式
const getCourseTypeTag = (type) => {
  const map = {
    '1': 'info',
    '2': 'success',
    '3': 'warning',
    '4': 'danger'
  }
  return map[type] || ''
}
const updateTeachers = (data) => {
  teachers.value = data
}

const getSchoolTime = (row) => {
  if(row.scheduleType == '1'){
    return row.scheduleTime
  }else{
    if(row.repeatType == '1'){
      return '每天'+row.scheduleTime
    }else{
      let week = []
      row.repeatWeekly.forEach(el => {
        if(el == '1'){
          week.push("周一")
        }
        if(el == '2'){
          week.push("周二")
        }
        if(el == '3'){
          week.push("周三")
        }
        if(el == '4'){
          week.push("周四")
        }
        if(el == '5'){
          week.push("周五")
        }
        if(el == '6'){
          week.push("周六")
        }
        if(el == '7'){
          week.push("周日")
        }
      })
      
      return `每${week.join("、")} ${row.scheduleTime}`
    }
  }
}



// 初始化加载数据
onMounted(() => {
  fetchCourses()
})
</script>

<style scoped>
.course-management {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  align-items: center;
}

.search-item {
  margin-bottom: 0;
}

.search-buttons {
  grid-column: 1 / -1;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 8px;
}

.action-buttons {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
